package com.lw.leetcode.sort.b;

import java.util.Arrays;

/**
 *324. 摆动排序 II
 * [1,3,2,2,3,1]
 * [1,5,1,1,6,4]
 * [4,5,5,6]
 * [1]
 * [1,4,3,4,1,2,1,3,1,3,2,3,3]
 * @Author liw
 * @Date 2021/8/15 19:24
 * @Version 1.0
 */
public class WiggleSort {

    public static void main(String[] args){
        WiggleSort test = new WiggleSort();
        // [2, 3, 1, 2, 1, 3]
//        int[] arr = {1,1,2,2,3,3};
        int[] arr = {1,5,1,1,6,4};
//        int[] arr = {2,1,1};
//        int[] arr = {1,4,3,4,1,2,1,3,1,3,2,3,3};

//        int[] arr = {2,1, 4};
        test.wiggleSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public void wiggleSort(int[] nums) {
        int length = nums.length;
        Arrays.sort(nums);
        int b = (length + 1) >> 1;
        int[] arra = Arrays.copyOfRange(nums, 0, b);
        int[] arrb = Arrays.copyOfRange(nums, b, length);
        int index = 0;
        if ((length & 1) == 0) {
            for (int i = b - 1; i >= 0; i--) {
                nums[index++] = arra[i];
                nums[index++] = arrb[i];
            }
        } else {
            nums[index++] = arra[b - 1];
            for (int i = b - 2; i >= 0; i--) {
                nums[index++] = arrb[i];
                nums[index++] = arra[i];
            }
        }
    }

}
